package com.itheima.controller;

import com.itheima.domain.User;
import com.itheima.service.UserService;
import com.itheima.service.impl.UserServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

@WebServlet("/userServlet")
public class UserServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        //1 接收请求参数并且使用BeanUtils封装
        User user=new User();
        try {
            BeanUtils.populate(user,request.getParameterMap());
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        //2 验证码校验
        //2.1 获取客户端浏览器发送过来的验证码
        String c_checkCode = request.getParameter("checkcode");
        //2.2 获取服务器session中保存的验证码
        String s_checkCode = (String) request.getSession().getAttribute("CHECKCODE_SERVER");
        //3.3 忽略大小写比较,如果校验失败,就将错误信息回显到注册页面
        if(!(c_checkCode!=null && c_checkCode.equalsIgnoreCase(s_checkCode))){
            //就将错误信息回显到注册页面
//            response.getWriter().write("验证码不正确");
            //向request域报错误信息
            request.setAttribute("errorMsg","验证码不正确");
            //请求转发到index.jsp页面
            request.getRequestDispatcher("/index.jsp").forward(request,response);
        }

        //3 调用service层方法,添加用户信息
        UserService userService=new UserServiceImpl();
        int count = userService.regist(user);
        //4 根据结果页面跳转
        if(count>0){
            response.sendRedirect(request.getContextPath()+"/success.html");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
